<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\controller\Util;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 合伙人管理
 *
 * @icon fa fa-circle-o
 */
class Partner extends Backend
{
    
    /**
     * Partner模型对象
     * @var \app\admin\model\Partner
     */
    protected $model = null;
    /**
     * 是否开启Validate验证
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Partner;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("accountStatusList", $this->model->getAccountStatusList());
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','type','phone','nick_name','header','money',
                    'sex','age','last_login_time','new_message_num','new_notification_num',
                    'register_time','account_status','invite_code','remark']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    private function add2Admin($username, $password, $email = '', $mobile = '',$nick_name='', $extend = [])
    {
        //账号注册时需要开启事务,避免出现垃圾数据
        try {
            $params['username'] = $username;
            $params['nickname'] = $nick_name;
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($password) . $params['salt']);
            $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            Db::name("admin")->insert($params);
            return Db::getLastInsID();
        } catch (\Exception $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                // 数据校验START
                $data = $this->validate($params, [
                    'phone' => 'require|regex:/^1[3456789]\d{9}$/',
                    'password' => 'require|regex:/^[0-9a-z_.]{8,16}$/i',
                ], [
                        'phone.require' => '手机号码必填',
                        'phone.regex' => '手机号码格式错误',
                        'password.require' => '密码为必填',
                        'password.regex' => '密码格式为8-16位大小写字母、数字、特殊符号',
                    ]
                );
                if (!empty($data) && $data !== true) {
                    return $this->error($data);
                }
                //数据校验 OVER

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
//                  添加到admin表中
                    $this->add2Admin($params['phone'],$params['password'],'',$params['phone'],$params['nick_name'],[]);
                    $admin_id = Db::name('admin')->getLastInsID();
//                    区域合伙人添加到 auth_group_access
                    Db::name("auth_group_access")->insert(['uid' => $admin_id, 'group_id' => 6]);
                    unset($params['password']);
                    $params['admin_id']=$admin_id;
                    $params['invite_code'] = Util::getInviteCode();
                    $params['register_time'] = date("Y-m-d H:i:s");
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $mystatus = $params['account_status'];
                    $params['id'] = input("ids");
                    $partner = Db::name('partner')->where('id',$params['id'])->find();
                    Util::changeAdminOrUser($partner['admin_id'],$mystatus,'');
                /*    switch ($mystatus){
                        case '0':
                            $myupdate['id']=$partner['admin_id'];
                            $myupdate['status']='normal';
                            Db::name('admin')->update($myupdate);
                            break;
                        case '1':
                            $myupdate['id']=$partner['admin_id'];
                            $myupdate['status']='hidden';
                            Db::name('admin')->update($myupdate);
                            break;
                        default:
                            break;

                    }*/
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
